package io.renren.modules.workflow.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import io.renren.common.utils.AjaxResult;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.workflow.dao.ActBusModuleConnectionMapper;
import io.renren.modules.workflow.dao.ActBusWorkflowDataMapper;
import io.renren.modules.workflow.entity.ActBusModelDefinition;
import io.renren.modules.workflow.entity.ActBusWorkflowData;
import io.renren.modules.workflow.entity.dto.ActBusProcessNode;
import io.renren.modules.workflow.entity.dto.ActBusTaskApproval;
import io.renren.modules.workflow.entity.dto.ActBusTaskVo;
import io.renren.modules.workflow.enums.ActBusSpecialBusinessEnum;
import io.renren.modules.workflow.enums.ActBusTaskApprovalEnum;
import io.renren.modules.workflow.enums.ActBusWorkFlowStatusEnum;
import io.renren.modules.workflow.service.IActBusModelDefinitionService;
import io.renren.modules.workflow.service.IActBusTaskService;
import io.renren.modules.workflow.utils.ActBusActivitiUtils;
import io.renren.modules.workflow.utils.ActBusBusinessUtils;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Desc 流程任务service实现
 * @Author landlord
 * @Date 2021/7/30 17:31
 */
@Service
public class ActBusTaskServiceImpl implements IActBusTaskService{
  @Autowired
  private ActBusWorkflowDataMapper actBusWorkflowDataMapper;
  @Autowired
  private ActBusActivitiUtils actBusActivitiUtils;
  @Autowired
  private TaskService taskService;
  @Autowired
  private RuntimeService runtimeService;
  @Autowired
  private HistoryService historyService;
  @Autowired
  private ActBusModuleConnectionMapper actBusModuleConnectionMapper;
  @Autowired
  private IActBusModelDefinitionService actBusModelDefinitionService;
    /**
     * @Desc: 我的发起流程查询 列表
     * @auther: landlord
     * @date: 2021/7/30 17:35
     * @return:
     */
    @Override
    public List<ActBusWorkflowData> selectMyProcessByUserList(ActBusWorkflowData actBusWorkflowData){

        return actBusWorkflowDataMapper.selectActBusWorkflowDataList(actBusWorkflowData);
    }

    /**
     * @Desc: 根据当前人 代办任务查询
     * @auther: landlord
     * @date: 2021/7/30 18:41
     * @return:
     */
    @Override
    public List<ActBusWorkflowData> selectTaskAgentsByUserList(ActBusWorkflowData actBusWorkflowData){
       //手动分页
       /* PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        Page<ActBusWorkflowData> page = new Page();

        TaskQuery taskQuery = taskService.createTaskQuery().
                taskAssignee(SecurityUtils.getUsername()).active().orderByTaskCreateTime().desc();
        Object startTime = actBusWorkflowData.getBeginTime();
        Object endTime = actBusWorkflowData.getEndTime();
        if(ObjectUtil.isNotNull(startTime) && ObjectUtil.isNotNull(endTime)){
            taskQuery.taskCreatedBefore(DateUtil.parse(startTime.toString(),"yyyy-MM-dd"));
            taskQuery.taskCreatedAfter(DateUtil.parse(endTime.toString(),"yyyy-MM-dd"));
        }
        List<Task> listTask = taskQuery.list();
        List<ActBusWorkflowData> resList =  new ArrayList<>();
        if(listTask!=null && listTask.size()>0){
            for(Task task : listTask){
                //根据当前任务的实例ID查询没有挂起的流程实例对象
                ProcessInstance  processInstance
                        = runtimeService.createProcessInstanceQuery().
                        processInstanceId(task.getProcessInstanceId()).active().singleResult();
                if(processInstance == null){
                    continue;
                }
                //获取业务Id
                String businessKey = processInstance.getBusinessKey();
                if(businessKey == null){
                    continue;
                }
                //得到业务对象
                ActBusWorkflowData resActBusWorkflowData =
                        actBusWorkflowDataMapper.selectActBusWorkflowDataById(Long.parseLong(businessKey));
                if(resActBusWorkflowData!=null){
                    ActBusTaskVo actBusTaskVo = new ActBusTaskVo(task.getId(),task.getName(),task.getTaskDefinitionKey(),task.getCreateTime(),task.getDueDate(),"");
                    resActBusWorkflowData.setActBusTaskVo(actBusTaskVo);
                    resList.add(resActBusWorkflowData);
                }
            }
        }
        page.setTotal(taskQuery.count());
        page.setPageNum(pageNum);
        page.setPages(pageSize);
        page.addAll(resList);*/
       // return page;
        return null;
    }


    /**
     * @Desc: 根据当前人 已办任务列表
     * @auther: landlord
     * @date: 2021/7/30 18:41
     * @return:
     */
    @Override
    public List<ActBusWorkflowData> selectHistoryTaskAgentsByUserList(ActBusWorkflowData actBusWorkflowData){
       /* //手动分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        Page<ActBusWorkflowData> page = new Page();

        HistoricTaskInstanceQuery taskInstanceQuery =
                historyService.createHistoricTaskInstanceQuery().
                finished().
                taskAssignee(SecurityUtils.getUsername()).
                orderByTaskCreateTime().desc();
        Object startTime = actBusWorkflowData.getBeginTime();
        Object endTime = actBusWorkflowData.getEndTime();
        if(ObjectUtil.isNotNull(startTime) && ObjectUtil.isNotNull(endTime)){
            taskInstanceQuery.taskCompletedBefore(DateUtil.parse(startTime.toString(),"yyyy-MM-dd"));
            taskInstanceQuery.taskCompletedAfter(DateUtil.parse(endTime.toString(),"yyyy-MM-dd"));
        }
        List<HistoricTaskInstance> historicTaskInstanceList = taskInstanceQuery.listPage((pageNum-1)*pageSize,pageSize);

        List<ActBusWorkflowData> resList = new ArrayList<>();
        if(historicTaskInstanceList!=null && historicTaskInstanceList.size()>0){
            for (HistoricTaskInstance taskHistoric : historicTaskInstanceList) {
                HistoricProcessInstance hProcessInstance =
                        historyService.createHistoricProcessInstanceQuery().
                                processInstanceId(taskHistoric.getProcessInstanceId()).finished().
                                singleResult();
                //得到业务对象
                if(hProcessInstance == null){
                    continue;
                }
                //获取业务Id
                String businessKey = hProcessInstance.getBusinessKey();
                if(businessKey == null){
                    continue;
                }

                //获取审核环节流程变量 作为流程状态
                HistoricVariableInstance historicVariableInstance =
                        historyService.createHistoricVariableInstanceQuery().
                                processInstanceId(taskHistoric.getProcessInstanceId()).
                                taskId(taskHistoric.getId()).
                                variableName(ActBusSpecialBusinessEnum.APPROVAL.getKey()).
                                singleResult();
              // ActBusWorkflowData actWorkflowData = new ActBusWorkflowData();
               // actWorkflowData.setAbwdWorkflowStatus(actBusWorkflowData.getAbwdWorkflowStatus());
                actBusWorkflowData.setAbwdId(Long.parseLong(businessKey));
                ActBusWorkflowData resActBusWorkflowData =
                        actBusWorkflowDataMapper.selectActBusWorkflowDataByWhere(actBusWorkflowData);
                if(StringUtils.isNotNull(resActBusWorkflowData)){
                    ActBusTaskVo actBusTaskVo = new ActBusTaskVo(taskHistoric.getId(),taskHistoric.getName(),taskHistoric.getTaskDefinitionKey(),hProcessInstance.getStartTime(),hProcessInstance.getEndTime(),ObjectUtil.isNotNull(historicVariableInstance)?historicVariableInstance.getValue().toString():"驳回");
                    resActBusWorkflowData.setActBusTaskVo(actBusTaskVo);
                    resList.add(resActBusWorkflowData);
                }

            }
        }
        page.setTotal(taskInstanceQuery.count());
        page.setPageNum(pageNum);
        page.setPages(pageSize);
        page.addAll(resList);
        return page;*/
        return null;
    }

    private boolean getBusinessAndHandle(ActBusWorkflowData resActBusWorkflowData, ActBusWorkflowData actBusWorkflowData) {

      return false;
    }

    /**
     * @Desc: 根据任务ID获取审批任务详细信息
     * @auther: landlord
     * @date: 2021/7/31 10:33
     * @return:
     */
    @Override
    public AjaxResult queryTaskAgentsDetails(String taskId){
       //根据登录人 任务ID 获取当前未挂起的审批的任务信息
       Task task =
               taskService.createTaskQuery().
                       taskAssignee(((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername()).
                       taskId(taskId).
                       active().
                       singleResult();
       if(task==null){
           return AjaxResult.error("当前任务已处理");
       }
        //根据当前任务的实例ID查询没有挂起的流程实例对象
        ProcessInstance  processInstance
                = runtimeService.createProcessInstanceQuery().
                processInstanceId(task.getProcessInstanceId()).active().singleResult();
        if(processInstance == null){
            return AjaxResult.error("流程实例已挂起,无法进行审批");
        }

        //获取业务Id
        String businessKey = processInstance.getBusinessKey();
        if(businessKey == null){
            return AjaxResult.error("流程业务标识不存在,无法进行审批");
        }
        //得到业务对象信息
        ActBusWorkflowData resActBusWorkflowData =
                actBusWorkflowDataMapper.selectActBusWorkflowDataById(Long.parseLong(businessKey));
        if(resActBusWorkflowData==null){
            return AjaxResult.error("流程业务数据不存在,无法进行审批");
        }
        ActBusTaskVo actBusTaskVo = new ActBusTaskVo(task.getId(),task.getName(),task.getTaskDefinitionKey());
        resActBusWorkflowData.setActBusTaskVo(actBusTaskVo);
        //获取流程xml信息
        String bpmnXml = actBusActivitiUtils.getBpmnXml(processInstance.getProcessDefinitionId());
        //返回结果
        Map<String,Object> resMap = new HashMap<>();
        resMap.put("workflowData",resActBusWorkflowData);
        resMap.put("bpmnXml",bpmnXml);
        resMap.put("processFlowInfo",selectFlowRecord(processInstance.getId()));//获取流程流转信息集合
        //获取业务数据总数
        return AjaxResult.success(resMap);
    }

    /**
     * @Desc: 根据实例ID获取历史已办列表
     * @auther: landlord
     * @date: 2021/7/31 10:33
     * @return:
     */
    @Override
    public AjaxResult queryHisTaskAgentsDetails(String processInstanceId){
        //根据登录人 任务ID 获取当前未挂起的审批的任务信息
        if(StrUtil.isEmpty(processInstanceId)){
            return AjaxResult.error("参数错误:无效的实例ID");
        }
        //根据当前任务的实例ID查询没有挂起的流程实例对象

        HistoricProcessInstance historicProcessInstance
                = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if(historicProcessInstance == null){
            return AjaxResult.error("历史流程实例已被删除");
        }
        //获取业务Id
        String businessKey = historicProcessInstance.getBusinessKey();
        if(businessKey == null){
            return AjaxResult.error("流程业务标识不存在,无法进行审批");
        }
        //得到业务对象信息
        ActBusWorkflowData resActBusWorkflowData =
                actBusWorkflowDataMapper.selectActBusWorkflowDataById(Long.parseLong(businessKey));
        if(resActBusWorkflowData==null){
            return AjaxResult.error("流程业务数据不存在,无法进行审批");
        }

        /*ActBusTaskVo actBusTaskVo = new ActBusTaskVo(task.getId(),task.getName(),task.getTaskDefinitionKey());
        resActBusWorkflowData.setActBusTaskVo(actBusTaskVo);*/
        //返回结果
        Map<String,Object> resMap = new HashMap<>();
        resMap.put("workflowData",resActBusWorkflowData);
        resMap.put("processFlowInfo",selectFlowRecord(historicProcessInstance.getId()));//获取流程流转信息集合
        return AjaxResult.success(resMap);
    }

    /**
     * @Desc: 获取流程历史流转记录
     * @auther: landlord
     * @date: 2021/8/4 9:13
     * @param procInsId 流程实例ID
     * @return:
     */
    public List<ActBusTaskVo> selectFlowRecord(String procInsId){
        List<HistoricActivityInstance> list =
                historyService.createHistoricActivityInstanceQuery().
                processInstanceId(procInsId).
                finished().
                activityType("userTask").
                orderByHistoricActivityInstanceStartTime().
                desc().list();
        List<ActBusTaskVo> listHisTaskVo = new ArrayList<>();
         if(list!=null && list.size()>0){
             for (HistoricActivityInstance histIns : list) {
                 ActBusTaskVo tv = new ActBusTaskVo();
                 tv.setTaskId(histIns.getTaskId());
                 tv.setTaskDefKey(histIns.getProcessDefinitionId());
                 tv.setTaskName(histIns.getActivityName());
                 tv.setStartTime(histIns.getStartTime());
                 tv.setEndTime(histIns.getEndTime());
                 /*if(StrUtil.isNotEmpty(histIns.getAssignee())){
                     SysUser sysUser =
                             actBusModuleConnectionMapper.selectUserByUserNameAct(histIns.getAssignee());
                     tv.setAssigneeName(sysUser.getUserName()+"("+sysUser.getNickName()+")");
                     tv.setAuditDeptName(sysUser.getDept().getDeptName());
                 }*/
                 //设置意见信息
                 List<Comment> cmList
                         = taskService.getTaskComments(histIns.getTaskId(),"comment");
                 tv.setComment((cmList!=null && cmList.size()>0)?cmList.get(0).getFullMessage():"");
                 //获取审核环节流程变量 作为流程状态
                 HistoricVariableInstance historicVariableInstance =
                         historyService.createHistoricVariableInstanceQuery().
                                 processInstanceId(histIns.getProcessInstanceId()).
                                 taskId(histIns.getTaskId()).
                                 variableName(ActBusSpecialBusinessEnum.APPROVAL.getKey()).
                                 singleResult();
                 tv.setAuditStatus(ObjectUtil.isNotNull(historicVariableInstance)?historicVariableInstance.getValue().toString():"驳回");
                 listHisTaskVo.add(tv);
             }
         }
        return listHisTaskVo;
    }


    /**
     * @Desc: 获取可以退回的审批节点
     * @auther: landlord
     * @date: 2021/8/10 19:28
     * @return:
     */
    @Override
    public AjaxResult GetBackToTheNodes(String taskId){
        Task task =
                taskService.createTaskQuery().taskId(taskId).active().singleResult();
        if(task == null){
            return AjaxResult.error("当前任务已经被处理,或者没有权限");
        }
        //流程定义ID
      String processDefinitionId = task.getProcessDefinitionId();
        //流程节点ID
      String currentNodeId = task.getTaskDefinitionKey();
      //得到当前环节可驳回的任务节点集合
       List<ActBusProcessNode> canBackNodes =
               actBusActivitiUtils.getCanBackNodes(currentNodeId, processDefinitionId);
       if(canBackNodes!=null && canBackNodes.size()>0){
           return AjaxResult.success(canBackNodes);
       }
        return AjaxResult.error("没有可以驳回的节点");
    }
    /**
     * @Desc: 任务审批 同意或者驳回
     * @auther: landlord
     * @date: 2021/8/2 12:43
     * @return:
     */
    @Override
    @Transactional
    public AjaxResult TaskApproval(ActBusTaskApproval actBusTaskApproval) throws Exception {
        if(StrUtil.isEmpty(actBusTaskApproval.getTaskId())){
            return AjaxResult.error("审批任务ID参数无效");
        }
        Task task =
                taskService.createTaskQuery().taskId(actBusTaskApproval.getTaskId()).active().singleResult();
        if(task == null){
            return AjaxResult.error("当前任务已处理完成");
        }
        //定义任务变量
         Map<String,Object> vars = new HashMap<>();
        //定义办理人
        String userName = "";//SecurityUtils.getUsername();
        //定义实例ID
        String processInstanceId = task.getProcessInstanceId();
        //当前实例对象
        ProcessInstance processInstanceCurrent =
                runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        //得到业务对象ID
       String businessKey = processInstanceCurrent.getBusinessKey();
       try {
           //标识 发起完成任务
           String checkNode = actBusTaskApproval.getCheckNode();
           if(StrUtil.isNotEmpty(checkNode) && checkNode.equals(ActBusSpecialBusinessEnum.START.getKey())){
               //发起完成任务
               return  CompleteByTask(actBusTaskApproval);
           }else{
               //获取任务环境变量
               vars = actBusActivitiUtils.getTaskVariables(task.getId());
               //同意
               if(ActBusTaskApprovalEnum.AGREE.getKey() == actBusTaskApproval.getAuthStatus()){  //同意
                  //设置任务同意变量
                   vars.put(ActBusSpecialBusinessEnum.APPROVAL.getKey(),"同意");
                   //通过 方法
                   return TaskApprovalAgree(actBusTaskApproval,vars,userName,task,processInstanceId,businessKey);
               }else if(ActBusTaskApprovalEnum.REJECTED.getKey() == actBusTaskApproval.getAuthStatus()){ //驳回
                   //设置任务驳回变量
                   vars.put(ActBusSpecialBusinessEnum.APPROVAL.getKey(),"驳回");
                   return TaskApprovalRejected(actBusTaskApproval,vars,task,userName,businessKey);
               }else {
                   return AjaxResult.error("审批类型无效");
               }
           }
       }catch (RuntimeException e){
           throw new Exception("任务审批失败,请联系管理员");
       }

    }

    /**
     * @Desc: 在流程实例启动时或者在我的流程中发起申请时完成的任务提交
     * @auther: landlord
     * @date: 2021/8/10 10:39
     * @return:
     */
    public AjaxResult CompleteByTask(ActBusTaskApproval actBusTaskApproval){
        Task task = actBusActivitiUtils.getCurrentTaskOrCurrentUserTaks(actBusTaskApproval.getTaskId(),null);
        if(task==null){
            return AjaxResult.error("当前任务已完结或者没有权限");
        }
        String taskId = task.getId();
        String userName = "";//SecurityUtils.getUsername();
        //根据任务ID 获取流程变量
        //得到当前任务流程变量
        Map<String,Object> taskVariables = actBusActivitiUtils.getTaskVariables(taskId);
        //设置任务办理人
        taskService.setAssignee(taskId,userName);
        //获取任务流程变量
        taskVariables.put(ActBusSpecialBusinessEnum.APPROVAL.getKey(),"发起");
        taskService.addComment(taskId,task.getProcessInstanceId(),"提交申请");
        //完成任务
        Authentication.setAuthenticatedUserId(userName);
        actBusActivitiUtils.comoleteByVariables(taskId,taskVariables,true);
        //处理设置了下一个环节办理人业务情况
        if(StrUtil.isNotEmpty(actBusTaskApproval.getNextAssignee())){
            //获取下一个任务
            Task taskNext = taskService.createTaskQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            if(taskNext != null){
                if(StrUtil.isNotEmpty(actBusTaskApproval.getNextAssignee())){
                    actBusActivitiUtils.setAssignTask(taskNext.getId(),actBusTaskApproval.getNextAssignee());
                    //发送消息提醒
                    /*Info info = new Info();
                    info.setSenduserid(userName);
                    info.setAcceptuserid(actBusTaskApproval.getNextAssignee());
                    info.setContent("您有一个流程审批单需要处理");
                    info.setPath("/staticProcess/view/"+taskNext.getId()+"?processType=audit");
                    info.setInfotype(5L);
                    info.setCheckUserName(true);
                    pushService.pushMsgToOne(info);*/
                }
            }
        }
        //修改业务数据状态为审核中
        //当前实例对象
        ProcessInstance processInstanceCurrent =
                runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        if(processInstanceCurrent==null){
            return AjaxResult.success("流程已结束");
        }
        //得到业务对象ID
        String businessKey = processInstanceCurrent.getBusinessKey();
        ActBusWorkflowData abwfd = new ActBusWorkflowData();
        abwfd.setAbwdWorkflowStatus(ActBusWorkFlowStatusEnum.INREVIEW.getKey());
        abwfd.setAbwdId(Long.parseLong(businessKey));
       if(actBusWorkflowDataMapper.updateActBusWorkflowData(abwfd)>0){
           return AjaxResult.success("发起成功");
       }else{
           return AjaxResult.error("发起失败");
       }
    }

    /**
     * @Desc: 审批之 通过业务处理
     * @auther: landlord
     * @date: 2021/8/4 11:15
     * @return:
     */
    public AjaxResult TaskApprovalAgree(ActBusTaskApproval actBusTaskApproval,
                                        Map<String,Object> vars,
                                        String userName,
                                        Task task,
                                        String processInstanceId,
                                        String businessKey){
        //设置批注人
        Authentication.setAuthenticatedUserId(userName);
        //添加审批意见
        actBusActivitiUtils.addComment(task,StrUtil.isNotEmpty(actBusTaskApproval.getApprovalOpinion())?actBusTaskApproval.getApprovalOpinion():"审批同意");
        //办理任务
        actBusActivitiUtils.comoleteByVariables(task.getId(),vars,true);
        //查询流程实例
        ProcessInstance processInstance =
                runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if(null == processInstance){ //表示流程已经结束
            //修改业务状态为审批完成
            ActBusWorkflowData abwd = new ActBusWorkflowData();
            abwd.setAbwdWorkflowStatus(ActBusWorkFlowStatusEnum.PASS.getKey());
            //abwd.setUpdateBy(SecurityUtils.getUsername() + "(" + SecurityUtils.getLoginUser().getUser().getNickName() + ")");
            abwd.setUpdateTime(new Date());
            abwd.setAbwdId(Long.parseLong(businessKey));
            actBusWorkflowDataMapper.updateActBusWorkflowData(abwd);

            //根据业务ID获取流程数据 找到发起人 发送消息
            ActBusWorkflowData abwdCom = actBusWorkflowDataMapper.selectActBusWorkflowDataById(Long.parseLong(businessKey));
            //发送消息提醒
            /*Info info = new Info();
            info.setSenduserid(userName);
            info.setAcceptuserid(abwdCom.getAbwdUserId());
            info.setContent("您有一个流程审批单处理完成");
            info.setPath("/staticProcess/view/"+abwdCom.getAbwdInstanceId()+"?processType=view");
            info.setInfotype(5L);
            info.setCheckUserName(true);
            pushService.pushMsgToOne(info);*/
            return AjaxResult.success("办理成功");
        }else{
            //重新提交的状态 为审批中
            ActBusWorkflowData abwd = new ActBusWorkflowData();
            abwd.setAbwdWorkflowStatus(ActBusWorkFlowStatusEnum.INREVIEW.getKey());
            abwd.setAbwdId(Long.parseLong(businessKey));
            actBusWorkflowDataMapper.updateActBusWorkflowData(abwd);
        }
       //处理设置了下一个环节办理人业务情况
        if(StrUtil.isNotEmpty(actBusTaskApproval.getNextAssignee())){
            //获取下一个任务
            Task taskNext = taskService.createTaskQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            if(taskNext != null){
                actBusActivitiUtils.setAssignTask(taskNext.getId(),StrUtil.isEmpty(actBusTaskApproval.getNextAssignee())?userName:actBusTaskApproval.getNextAssignee());
                //发送消息提醒
                /*Info info = new Info();
                info.setSenduserid(userName);
                info.setAcceptuserid(actBusTaskApproval.getNextAssignee());
                info.setContent("您有一个流程审批单需要处理");
                info.setPath("/staticProcess/view/"+taskNext.getId()+"?processType=audit");
                info.setInfotype(5L);
                info.setCheckUserName(true);
                pushService.pushMsgToOne(info);*/
            }
        }
        return AjaxResult.success("办理成功");
    }

    /**
     * @Desc: 流程办理-驳回
     *        驳回到发起、驳回到上一节点 结束流程 驳回任意审批节点
     * @auther: landlord
     * @date: 2021/8/4 12:19
     * @return:
     */
    public AjaxResult TaskApprovalRejected(ActBusTaskApproval actBusTaskApproval,Map<String,Object> vars,
                                           Task task,String userName,String businessKey) throws Exception {
         //发起者
        if(actBusTaskApproval.getRejectedType().equals(ActBusSpecialBusinessEnum.REJECTEDTYPEINITIATE.getKey())){

            //流程驳回到发起者
            actBusActivitiUtils.nodeJumpTo(task.getId(),vars.get("firstNodeId").toString(),userName,vars,StrUtil.isEmpty(actBusTaskApproval.getApprovalOpinion())?"审批驳回":actBusTaskApproval.getApprovalOpinion());

            //获取驳回后的任务
            Task taskRejected = taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).active().singleResult();

            //修改业务数据
            ActBusWorkflowData abwd = new ActBusWorkflowData();
            abwd.setAbwdTaskId(taskRejected.getId());
            abwd.setAbwdWorkflowStatus(ActBusWorkFlowStatusEnum.REJECTED.getKey());
            abwd.setAbwdId(Long.parseLong(businessKey));
            if(actBusWorkflowDataMapper.updateActBusWorkflowData(abwd)>0){
                //根据业务ID获取流程数据 找到发起人 发送消息
                ActBusWorkflowData abwdCom = actBusWorkflowDataMapper.selectActBusWorkflowDataById(Long.parseLong(businessKey));
                //发送消息提醒
                /*Info info = new Info();
                info.setSenduserid(userName);
                info.setAcceptuserid(abwdCom.getAbwdUserId());
                info.setContent("您有一个流程申请单被驳回");
                info.setPath("/staticProcess/view/"+taskRejected.getProcessInstanceId()+"?processType=reject");
                info.setInfotype(5L);
                info.setCheckUserName(true);
                pushService.pushMsgToOne(info);*/
                return AjaxResult.success("驳回到发起人成功");
            }else{
                return AjaxResult.success("驳回失败");
            }
         }//上一环节
         else if(actBusTaskApproval.getRejectedType().equals(ActBusSpecialBusinessEnum.REJECTEDTYPEON.getKey())){
            //设置批注人
            Authentication.setAuthenticatedUserId(userName);
            //添加审批意见
            actBusActivitiUtils.addComment(task,actBusTaskApproval.getApprovalOpinion());
            //驳回到上一个环节
           actBusActivitiUtils.dismissedOnALink(task.getId(),vars);
            //修改业务状态
            ActBusWorkflowData abwd = new ActBusWorkflowData();
            abwd.setAbwdWorkflowStatus(ActBusWorkFlowStatusEnum.REJECTED.getKey());
            abwd.setAbwdId(Long.parseLong(businessKey));
            actBusWorkflowDataMapper.updateActBusWorkflowData(abwd);

            return AjaxResult.success("驳回操作成功");
         }//结束流程
         else if(actBusTaskApproval.getRejectedType().equals(ActBusSpecialBusinessEnum.REJECTEDSPECIFIEDNODE.getKey())){
            //驳回指定节点
            actBusActivitiUtils.nodeJumpTo(task.getId(),actBusTaskApproval.getActivitiId(),userName,vars,StrUtil.isEmpty(actBusTaskApproval.getApprovalOpinion())?"审批驳回":actBusTaskApproval.getApprovalOpinion());
            //表示发起节点
            if(vars.get("firstNodeId").equals(actBusTaskApproval.getActivitiId())){
                //修改业务数据为驳回状态
                //获取驳回后的任务
                Task taskRejected = taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).active().singleResult();
                //修改业务数据
                ActBusWorkflowData abwd = new ActBusWorkflowData();
                abwd.setAbwdTaskId(taskRejected.getId());
                abwd.setAbwdWorkflowStatus(ActBusWorkFlowStatusEnum.REJECTED.getKey());
                abwd.setAbwdId(Long.parseLong(businessKey));
                actBusWorkflowDataMapper.updateActBusWorkflowData(abwd);
                ActBusWorkflowData abwdCom = actBusWorkflowDataMapper.selectActBusWorkflowDataById(Long.parseLong(businessKey));
                //发送消息提醒
                /*Info info = new Info();
                info.setSenduserid(userName);
                info.setAcceptuserid(abwdCom.getAbwdUserId());
                info.setContent("您有一个流程申请单被驳回");
                info.setPath("/staticProcess/view/"+taskRejected.getId()+"?processType=reject");
                info.setInfotype(5L);
                info.setCheckUserName(true);
                pushService.pushMsgToOne(info);*/

            }else{
                List<HistoricActivityInstance> historicActivityInstanceList  =
                        historyService.createHistoricActivityInstanceQuery().
                                processInstanceId(task.getProcessInstanceId()).
                                activityId(actBusTaskApproval.getActivitiId()).
                                orderByHistoricActivityInstanceEndTime().desc().
                                finished().list();
                String assignee = historicActivityInstanceList.get(0).getAssignee();
                Task taskRejected = taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).active().singleResult();
                taskService.setAssignee(taskRejected.getId(),assignee);
                //发送消息提醒
                /*Info info = new Info();
                info.setSenduserid(userName);
                info.setAcceptuserid(assignee);
                info.setContent("您有一个流程申请单被驳回");
                info.setPath("/staticProcess/view/"+taskRejected.getId()+"?processType=audit");
                info.setInfotype(5L);
                info.setCheckUserName(true);
                pushService.pushMsgToOne(info);*/
            }
            return AjaxResult.success("驳回操作成功");
         }else {
             return AjaxResult.error("无效的流程驳回类型参数");
         }
    }

    /**
     * @Desc: 任务驳回后 重新提交
     * @auther: landlord
     * @date: 2021/8/11 20:47
     * @return:
     */
    public AjaxResult resubmitTheTask(ActBusTaskApproval actBusTaskApproval) throws Exception {
            Task task = actBusActivitiUtils.getCurrentTaskOrCurrentUserTaks(actBusTaskApproval.getTaskId(),null);
            if(task==null){
                return AjaxResult.error("当前任务已完结或者没有权限");
            }
            String taskId = task.getId();
            String userName = "";//SecurityUtils.getUsername();
            //得到当前任务流程变量
            Map<String,Object> taskVariables = actBusActivitiUtils.getTaskVariables(taskId);
            //重新提交有可能流程变量会变更 需要重新构建流程任务变量
            Map<String,Object> varsForm = ActBusBusinessUtils.parseWorkFlowFormJson(actBusTaskApproval.getFormJson());
            //获取流程xml
           ActBusModelDefinition actBusModelDefinition =
                   actBusModelDefinitionService.selectActBusModelDefinitionDeployId(actBusTaskApproval.getAbmdDeployId());

        //设置流程启动流程变量
            Set<String> varsList = actBusActivitiUtils.getBpmnXmlAllVariables(actBusModelDefinition.getAbmdXml());
            if(varsList!=null && varsList.size()>0){
                varsList.forEach(key->{
                    if(!key.equals(ActBusSpecialBusinessEnum.APPROVAL.getKey())){
                        taskVariables.put(key,varsForm.get(key));
                    }
                });
            }
            //设置任务办理人
            taskService.setAssignee(taskId,userName);
            //获取任务流程变量
            taskVariables.put(ActBusSpecialBusinessEnum.APPROVAL.getKey(),"提交");
            taskService.addComment(taskId,task.getProcessInstanceId(),"重新提交");
            //完成任务
            Authentication.setAuthenticatedUserId(userName);
            //完成任务之前 修改任务环境变量
            runtimeService.setVariables(task.getProcessInstanceId(),taskVariables);
            //完成任务
            actBusActivitiUtils.comoleteByVariables(taskId,taskVariables,true);
            //处理设置了下一个环节办理人业务情况
            if(StrUtil.isNotEmpty(actBusTaskApproval.getNextAssignee())){
                //获取下一个任务
                Task taskNext = taskService.createTaskQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .singleResult();
                if(taskNext != null){
                    if(StrUtil.isNotEmpty(actBusTaskApproval.getNextAssignee())){
                        actBusActivitiUtils.setAssignTask(taskNext.getId(),actBusTaskApproval.getNextAssignee());

                        //发送消息提醒
                        /*Info info = new Info();
                        info.setSenduserid(userName);
                        info.setAcceptuserid(actBusTaskApproval.getNextAssignee());
                        info.setContent("您有一个流程申请单需要审批");
                        info.setPath("/staticProcess/view/"+taskNext.getId()+"?processType=audit");
                        info.setInfotype(5L);
                        info.setCheckUserName(true);
                        pushService.pushMsgToOne(info);*/

                    }
                }
            }
            //修改业务数据状态为审核中
            //当前实例对象
            ProcessInstance processInstanceCurrent =
                    runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
            if(processInstanceCurrent==null){
                return AjaxResult.success("流程已结束");
            }
            //得到业务对象ID
            String businessKey = processInstanceCurrent.getBusinessKey();
            ActBusWorkflowData abwfd = new ActBusWorkflowData();
            abwfd.setAbwdWorkflowStatus(ActBusWorkFlowStatusEnum.INREVIEW.getKey());
            abwfd.setAbwdFormJson(actBusTaskApproval.getFormJson());
            abwfd.setAbwdId(Long.parseLong(businessKey));
            if(actBusWorkflowDataMapper.updateActBusWorkflowData(abwfd)>0){
                return AjaxResult.success("重新提交成功");
            }else{
                return AjaxResult.error("重新提交失败");
            }
    }




}
